/**
 * @file: InsertThread.java
 *
 * @author: 蒋振
 *
 * @date: 2016年4月1日 下午2:20:32
 *
 * @copyright: 南京凯盛
 */
package cn.com.kisen.db.mongo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


/**
 *
 *
 * @author 蒋振
 * @version 1.0 Created on 2016年4月1日 下午2:20:32
 */
public class InsertThread implements Runnable {

    private Logger logger = Logger.getLogger(InsertThread.class);

    private String collectionName;

    public InsertThread(String collectionName){
        this.collectionName = collectionName;
    }

    public Date batchInsert(Date date){
        // 批量插入的数据量 1000ms*60 = 1min
        int  batchSize = 60000;
        long start = new Date().getTime();

        MongoClientPool pool = MongoClientPool.getInstance();
        MongoClient client = pool.getMongoClient();
        MongoDatabase mongoDatabase = client.getDatabase("test");
        MongoCollection<Document> collection = mongoDatabase.
                getCollection(collectionName);
        List<Document> documents = new ArrayList<Document>();
        for(int i=0;i<batchSize;i++){

            Random random = new Random();
            Document document = new Document("_id",new Date(date.getTime()+i)).
                    append("value", random.nextDouble());
            documents.add(document);
        }
        collection.insertMany(documents);
        long runtime = new Date().getTime() - start;
        logger.debug("向" + collectionName +"插入六万条数据 ,用时" + runtime + "ms");
        pool.dropMongoClient(client);
        return new Date(date.getTime()+batchSize);
    }

    public void run() {
        Date date = new Date();
        for(int i=0;i< 24;i++){
            date = batchInsert(date);
        }
    }

}
